﻿using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using OnlineLearningSystem.IRepository;
using OnlineLearningSystem.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace OnlineLearningSystem.Controllers
{
    /// <summary>
    /// 批次管理
    /// </summary>
    public class BatchController : BaseController
    {
        private readonly IConfiguration _configuration;
        public BatchController(IUserRepository userService, ICourseRepository courseService,
            IBatchRepository batchService, ILearningSituationRepository learningSituationService,
            ITestRepository testService, ITopicRepository topicService, IConfiguration configuration)
            : base(userService, courseService, batchService, learningSituationService, testService, topicService)
        {
            _configuration = configuration;
        }

        /// <summary>
        ///批次添加
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public JsonResult AddBatch(Batch batch,string users, string courses)
        {

            int code = 0;
            string message = "";
            try
            {
                code = 200;
                message = "提交成功！";
                string[] strusers = users.Split(','); //字符串转数组
                string[] strcourses = courses.Split(','); //字符串转数组
                batch.Courses = new List<Course>();
                batch.Users = new List<User>();
                foreach (var item in strusers) {
                    batch.Users.Add(_userService.Get(o=>o.ID==int.Parse(item)));
                }
                foreach (var item in strcourses)
                {
                    batch.Courses.Add(_courseService.Get(o => o.ID == int.Parse(item)));
                }
                batch.state = 0;
                _batchService.Create(batch);
            }
            catch
            {
                code = 500;
                message = "提交失败！";
            }
            return new JsonResult(new { code, message });
        }

        /// <summary>
        /// 批次删除
        /// </summary>
        /// <param name="batchId"></param>
        /// <returns></returns>
        [HttpPost]
        public JsonResult batchDelete(int batchId)
        {
            int code = 0;
            string message = "";
            Batch batch = _batchService.Get(o => o.ID == batchId);


            if (batch == null)
            {
                code = 500;
                message = "课程不存在";
            }
            else
            {
                code = 200;
                message = "删除成功！";
                _batchService.Delete(batch);
            }
            return new JsonResult(new { code, message });
        }

    }
}
